package middleware

import (
	"errors"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"gitee.com/monkeyPP/happy-mall/services/userservice/internal/pkg/auth"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从Authorization头获取token
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, errors.New("缺少Authorization头"))
			c.Abort()
			return
		}

		// 验证Authorization头格式 (Bearer <token>)
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.JSON(http.StatusUnauthorized, errors.New("Authorization头格式错误，应为 Bearer <token>"))
			c.Abort()
			return
		}

		// 解析和验证JWT
		tokenString := parts[1]
		claims, err := auth.ValidateAccessToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, errors.New("无效的token: "+err.Error()))
			c.Abort()
			return
		}

		c.Set("userID", claims.UserID)
		c.Next()
	}
}
